import json
import os


def validate_adjacent_fractals(data):
    length = len(data)
    for i in range(length - 1):
        if data[i]['top_fractal']:
            for j in range(i + 1, length):
                if data[j]['bottom_fractal']:
                    if data[i]['high'] <= data[j]['low']:
                        data[i]['top_fractal'] = False
                        data[j]['bottom_fractal'] = False
                    break
        elif data[i]['bottom_fractal']:
            for j in range(i + 1, length):
                if data[j]['top_fractal']:
                    if data[i]['low'] >= data[j]['high']:
                        data[i]['bottom_fractal'] = False
                        data[j]['top_fractal'] = False
                    break
    return data


def validate_all_fractals(data):
    validated = False
    while not validated:
        initial_data = json.dumps(data)
        data = validate_adjacent_fractals(data)
        validated = (initial_data == json.dumps(data))
    return data


def load_data(file_path):
    with open(file_path, 'r') as f:
        return json.load(f)


def save_data(data, file_path):
    with open(file_path, 'w') as f:
        json.dump(data, f, indent=4)


if __name__ == "__main__":
    base_path = os.path.dirname(os.path.abspath(__file__))
    input_file = os.path.join(base_path, '../static/validated_processed_bnb_usdt_klines.json')
    output_file = os.path.join(base_path, '../static/final_validated_processed_bnb_usdt_klines.json')

    data = load_data(input_file)

    # Validate adjacent fractals until no changes are needed
    validated_data = validate_all_fractals(data)

    # Save the final validated data
    save_data(validated_data, output_file)

    print(f"Final validated processed fractals have been saved to {output_file}")
